﻿namespace PauloMorgado.SharePoint.Services
{
    using PauloMorgado.SharePoint.Services.Lists;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.ServiceModel;
    using System.Xml.Linq;

    public static class ServiceHelper
    {
        public static ChannelFactory<TService> CreateChannelFactory<TService>(Uri baseUri, string relativeUri, HttpClientCredentialType credentialType, NetworkCredential credential)
        {
            if (!baseUri.AbsoluteUri.EndsWith("/") && !relativeUri.StartsWith("/"))
            {
                relativeUri = '/' + relativeUri;
            }

            var endpointAddress = new EndpointAddress(new Uri(baseUri, relativeUri));
            return CreateChannelFactory<TService>(endpointAddress, credentialType, credential);
        }

        public static ChannelFactory<TService> CreateChannelFactory<TService>(EndpointAddress endpointAddress, HttpClientCredentialType credentialType, NetworkCredential credential)
        {
            var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
            binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            binding.Security.Transport.ClientCredentialType = credentialType;

            var channelFactory = new ChannelFactory<TService>(binding, endpointAddress);

            channelFactory.Credentials.Windows.ClientCredential = credential;

            return channelFactory;
        }

        public static IEnumerable<XElement> GetAllListItems(Request request)
        {
            var credential = string.IsNullOrEmpty(request.UserName) ? new NetworkCredential() : new NetworkCredential(request.UserName, request.Password);
            var listsService = ListsService.CreateListsChannel(request.SiteUri, request.HttpClientCredentialType, credential);

            var getListItemsRequest = new GetListItemsRequest
            {
                Body = new GetListItemsRequestBody
                {
                    listName = request.ListName/*,
                    viewName = viewId*/
                }
            };

            if (request.FieldNames != null)
            {
                getListItemsRequest.Body.viewFields = new XElement("{http://schemas.microsoft.com/sharepoint/soap/}ViewFields",
                    from fieldName in request.FieldNames
                    select new XElement("{http://schemas.microsoft.com/sharepoint/soap/}FieldRef", new XAttribute("Name", fieldName.Trim())));
            }

            if (request.Query != null)
            {
                getListItemsRequest.Body.query = request.Query;
            }

            if (request.QueryOptions != null)
            {
                getListItemsRequest.Body.queryOptions = request.QueryOptions;
            }

            return listsService.GetAllListItems(getListItemsRequest);
        }

        public static XElement LoadElement(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return null;
            }

            var dummy = XElement.Parse(
                string.Format("<dummy xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">{0}</dummy>", content),
                LoadOptions.None);

            var node = dummy.FirstNode;

            return node as XElement;
        }
    }
}
